package ru.ifmo.swing.genetics.config.operator;

import org.uncommons.maths.number.NumberGenerator;
import org.uncommons.watchmaker.framework.EvaluatedCandidate;
import org.uncommons.watchmaker.framework.EvolutionaryOperator;
import ru.ifmo.automaton.Automaton;
import ru.ifmo.common.Source;
import ru.ifmo.genetics.adaptation.AdaptableParameter;
import ru.ifmo.genetics.crossover.string.VaryingLengthStringCrossover;
import ru.ifmo.swing.EvolutionControlWithConfigProvider;
import ru.ifmo.swing.Panel;

import javax.swing.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author avhaliullin
 */
public class VaryingLengthStringCrossoverControl implements
        EvolutionaryOperator<String>,
        EvolutionControlWithConfigProvider,
        AdaptableParameter<String> {
    private final CorrectingProbabilityControl probabilityControl;
    private final Panel control;
    private final VaryingLengthStringCrossover crossover;

    public VaryingLengthStringCrossoverControl(double defaultCrossoverProbability,
                                               Source<Automaton<Character, String>> automatonSource,
                                               NumberGenerator<Integer> maxLength) {
        probabilityControl = new CorrectingProbabilityControl(automatonSource, defaultCrossoverProbability, 0.01);
        control = new Panel();
        control.setHorizontal(false);

        Panel probability = new Panel();
        probability.setHorizontal(true);
        probability.add(new JLabel("Probability: "));
        probability.add(probabilityControl.getControl());
        control.add(probability);


        crossover = new VaryingLengthStringCrossover(probabilityControl, maxLength);
    }

    public JComponent getControl() {
        return control;
    }

    public void reset() {
        probabilityControl.reset();
    }

    public void setDescription(String description) {
        control.setTitle(description);
    }

    public List<String> apply(List<String> selectedCandidates, Random rng) {
        return crossover.apply(selectedCandidates, rng);
    }

    public void adapt(List<List<EvaluatedCandidate<String>>> lastGenerations) {
        probabilityControl.adapt(lastGenerations);
    }

    public Map<String, Object> getParamValues() {
        Map<String, Object> res = new HashMap<String, Object>();
        res.put("Probability", probabilityControl);
        return res;
    }
}
